#include<windows.h>
#include<iostream>
using namespace std;

int ticket = 100;
HANDLE hMutex; //定义互斥对象

DWORD WINAPI FuncProc1(LPVOID lpParameter);
DWORD WINAPI FuncProc2(LPVOID lpParameter);


int main()
{	
	hMutex = CreateMutex(NULL, FALSE, NULL); //定义互斥对象，并让该线程不拥有它
	HANDLE hThread1 = CreateThread(NULL, 0, FuncProc1, NULL, 0, NULL);
	HANDLE hThread2 = CreateThread(NULL,0, FuncProc2, NULL, 0, NULL);
	CloseHandle(hThread1);
	CloseHandle(hThread2);
	Sleep(1000); //让主线程睡眠1秒	 
	return 0;
}

DWORD WINAPI FuncProc1(LPVOID lpParameter) {
	while (true) {
		WaitForSingleObject(hMutex, INFINITE);
		if (ticket > 0) {
			Sleep(1);
			cout << "ticket1 :" << ticket-- << endl;
		}
		else
			break;
		ReleaseMutex(hMutex);
	}
	return 0;
}

DWORD WINAPI FuncProc2(LPVOID lpParameter) {
	while (true) {
		WaitForSingleObject(hMutex, INFINITE); //申请互斥对象的所有权
		if (ticket > 0) {
			Sleep(1);
			cout << "ticket2 :" << ticket-- << endl;
		}
		else
			break;
		ReleaseMutex(hMutex); //释放互斥对象的所有权
	}
	return 0;
}
